package com.huixh.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huixh.train.business.domain.DailyTrain;
import com.huixh.train.business.domain.DailyTrainExample;
import com.huixh.train.business.domain.Train;
import com.huixh.train.business.mapper.DailyTrainMapper;
import com.huixh.train.business.req.DailyTrainQueryReq;
import com.huixh.train.business.req.DailyTrainSaveReq;
import com.huixh.train.business.resp.DailyTrainQueryResp;
import com.huixh.train.business.service.*;
import com.huixh.train.common.exception.BusinessException;
import com.huixh.train.common.exception.BusinessExceptionEnum;
import com.huixh.train.common.resp.PageResult;
import com.huixh.train.utils.random.SnowUtil;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author huixh
 */
@Service
public class DailyTrainServiceImpl implements DailyTrainService {

    private final Logger logger = LoggerFactory.getLogger(DailyTrainServiceImpl.class);
    @Resource
    private DailyTrainMapper dailyTrainMapper;
    @Resource
    private TrainService trainService;
    @Resource
    private DailyTrainTicketService dailyTrainTicketService;
    @Resource
    private SnowUtil snowUtil;
    @Resource
    private DailyTrainStationService dailyTrainStationService;
    @Resource
    private DailyTrainCarriageService dailyTrainCarriageService;
    @Resource
    private DailyTrainSeatService dailyTrainSeatService;
    @Resource
    private SkTokenService skTokenService;
    @Override
    public void save(DailyTrainSaveReq dailyTrainSaveReq) {
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(dailyTrainSaveReq, DailyTrain.class);

        DailyTrain byUnique = getByUnique(dailyTrain.getCode(),dailyTrain.getDate());

        if (ObjectUtil.isNotNull(byUnique)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_CODE_EXISTS);
        }

        if (ObjectUtil.isNull(dailyTrain.getId())) {
            dailyTrain.setId(snowUtil.getSnowflakeToLong());
            dailyTrain.setCreateTime(now);
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.insert(dailyTrain);
        } else {
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.updateByPrimaryKey(dailyTrain);
        }
    }

    @Override
    public PageResult<List<DailyTrainQueryResp>> queryList(DailyTrainQueryReq dailyTrainQueryReq) {
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.setOrderByClause("`date` desc,`code` asc");
        DailyTrainExample.Criteria criteria = dailyTrainExample.createCriteria();

        if (StrUtil.isNotBlank(dailyTrainQueryReq.getTrainCode())) {
            criteria.andCodeEqualTo(dailyTrainQueryReq.getTrainCode());
        }

        if (ObjectUtil.isNotNull(dailyTrainQueryReq.getDate())) {
            criteria.andDateEqualTo(dailyTrainQueryReq.getDate());
        }

        logger.info("查询页码：{}", dailyTrainQueryReq.getPageNum());
        logger.info("每页条数：{}", dailyTrainQueryReq.getPageSize());
        PageHelper.startPage(dailyTrainQueryReq.getPageNum(), dailyTrainQueryReq.getPageSize());
        List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(dailyTrainExample);

        PageInfo<DailyTrain> pageInfo = new PageInfo<>(dailyTrainList);
        logger.info("总行数：{}", pageInfo.getTotal());
        logger.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainQueryResp> list = BeanUtil.copyToList(dailyTrainList, DailyTrainQueryResp.class);
        return PageResult.success(pageInfo.getTotal(), list);
    }

    @Override
    public void delete(Long id) {
        dailyTrainMapper.deleteByPrimaryKey(id);
    }

    public @Nullable DailyTrain getByUnique(String trainCode, Date date) {
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        DailyTrainExample.Criteria criteria = dailyTrainExample.createCriteria();
        criteria.andCodeEqualTo(trainCode);
        criteria.andDateEqualTo(date);
        List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(dailyTrainExample);
        if (CollUtil.isEmpty(dailyTrainList)) {
            return null;
        } else {
            return dailyTrainList.get(0);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void genDaily(Date date) {
        logger.info("生成日期【{}】车次信息开始", date);
        List<Train> trainList = trainService.selectAll();
        if (CollUtil.isEmpty(trainList)) {
            logger.info("没有车次数据，任务结束");
        }
        for (Train train : trainList) {
            genDailyTrain(date,train);
        }

    }
    @Transactional(rollbackFor = Exception.class)
    public void genDailyTrain(Date date,Train train) {
        DateTime now = DateTime.now();
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.createCriteria()
                .andCodeEqualTo(train.getCode())
                .andDateEqualTo(date);

        dailyTrainMapper.deleteByExample(dailyTrainExample);
        logger.info("生成日期【{}】车次【{}】信息开始", DateUtil.formatDate(date), train.getCode());

        DailyTrain dailyTrain = BeanUtil.copyProperties(train, DailyTrain.class);
        dailyTrain.setId(snowUtil.getSnowflakeToLong());
        dailyTrain.setDate(date);
        dailyTrain.setCreateTime(now);
        dailyTrain.setUpdateTime(now);

        dailyTrainMapper.insert(dailyTrain);
        // 生成每日车站数据
        dailyTrainStationService.genDailyTrainStation(train.getCode(), date);
        // 生成每日车站车厢数据
        dailyTrainCarriageService.genDailyTrainCarriage(train.getCode(),date);
        // 生成每日车次座位信息
        dailyTrainSeatService.genDailySeat(train.getCode(),date);
        // 生成车次余票数据信息
        dailyTrainTicketService.genDailyTrainTicket(date,train);
        // 生成车票令牌
        skTokenService.genDaily(date,train.getCode());

        logger.info("生成日期【{}】车次【{}】信息生成成功", DateUtil.formatDate(date), train.getCode());
    }
}